import React, { useCallback, useEffect, useRef, useState } from 'react';

export type CountDownProps = {
  /** 开始时间，单位秒 */
  start: number;
  /** 倒计时变化 */
  onChange?: (time: number) => void;
  /** 倒计时结束 */
  onTimeout?: () => void;
};

/** 倒计时组件 */
const useCountDown = ({
  start = 0,
  onChange,
  onTimeout,
}: CountDownProps): [number] => {
  const [leftTime, setLeftTime] = useState<number>(start);
  const now = Date.now();
  const timerId: React.MutableRefObject<any> = useRef(null);
  const timeRef: React.MutableRefObject<number> = useRef(start);

  const countHandle = useCallback<() => void>(() => {
    if (timeRef.current <= 0) {
      clearInterval(timerId.current);
      onTimeout && onTimeout();
      setLeftTime(0);
      return (timeRef.current = 0);
    }

    const count = Number(((Date.now() - now) / 1000).toFixed(0));
    const current = start - count < 0 ? 0 : start - count;
    timeRef.current = current;
    setLeftTime(current);
    onChange && onChange(current);
  }, [start]);

  useEffect(() => {
    if (start && start > 0) {
      timeRef.current = start;
      setLeftTime(start);
      timerId.current = setInterval(countHandle, 1000);
    }
    return () => {
      if (timerId.current) {
        clearInterval(timeRef.current);
      }
    };
  }, [start]);

  return [leftTime];
};

export { useCountDown };
